from account.account_service import AccountService, accounts_write_lock
from threading import Timer
from common.logger import logger
import common.http as http
import json
import spider_config


class YmiotAccountService(AccountService):
    def __init__(self, interval: int) -> None:
        super().__init__()
        self.__interval = interval

    def active(self):
        if not self._is_active:
            self.fetch()
            self._is_active = True

    def fetch(self):
        with accounts_write_lock:
            params = {"token_type": 2, "second": 500, "task_id": self._task_id}
            rsp = http.get(
                spider_config.park_token_host + "/api/parktoken/data", params
            )
            data = rsp.json()["data"]
            self._clear()
            for item in data:
                self._accounts.append(json.loads(item["data"]))
                # logger.success(f"补充云盟平台账号: {item}")

            logger.success(f"补充云盟平台账号完成，剩余账号数量: {len(self._accounts)}")
            self.timer = Timer(self.__interval, self.fetch, ()).start()

    def take(self):
        with accounts_write_lock:
            if not self._accounts:
                logger.error("云盟账号不足，尝试重新获取")
                self.fetch()
            return super().take()
